% Specify the folder containing the images
inputFolder = 'Folder Path'; % Update as needed

% Define subfolders for binary and filled binary images
binaryFolder = fullfile(inputFolder, 'Binary_Images');
filledFolder = fullfile(inputFolder, 'Filled_Binary_Images');

% Create the output folders if they don't exist
if ~exist(binaryFolder, 'dir')
    mkdir(binaryFolder);
end
if ~exist(filledFolder, 'dir')
    mkdir(filledFolder);
end

% Get a list of all JPG and PNG images in the folder
imageFiles = [dir(fullfile(inputFolder, '*.jpg')); dir(fullfile(inputFolder, '*.png'))];

% Check if any images were found
if isempty(imageFiles)
    disp('No images found in the specified folder.');
    return; % Exit script if no images are found
end

% Display the number of images found
disp(['Number of images found: ', num2str(length(imageFiles))]);

% Sensitivity setting for adaptive binarization (adjust as needed, range: 0 to 1)
sensitivity = 0.5; % Modify this value if needed

% Loop through each image in the folder
for k = 1:length(imageFiles)
    try
        % Construct the full image path
        imagePath = fullfile(inputFolder, imageFiles(k).name);
        
        % Read the image
        img = imread(imagePath);

        % Convert to grayscale if the image is RGB
        if size(img, 3) == 3
            img_gray = rgb2gray(img);
        else
            img_gray = img;
        end

        % Convert the grayscale image to binary using adaptive thresholding
        bw = imbinarize(img_gray, 'adaptive', 'ForegroundPolarity', 'dark', 'Sensitivity', sensitivity);

        % Generate filenames for output
        [~, fileName, ext] = fileparts(imageFiles(k).name);
        binaryImagePath = fullfile(binaryFolder, [fileName '_binary' ext]); % Keep same format as input
        filledImagePath = fullfile(filledFolder, [fileName '_filled' ext]);

        % Save the binary image
        imwrite(bw, binaryImagePath);

        % Invert the binary image to detect black particles as regions
        bw_inverted = ~bw;

        % Fill the black particles completely black
        filled_bw_inverted = imfill(bw_inverted, 'holes');

        % Invert back to the original binary format
        filled_bw = ~filled_bw_inverted;

        % Save the filled binary image
        imwrite(filled_bw, filledImagePath);

        % Display progress messages
        disp(['Processed: ', imageFiles(k).name]);
        disp(['Binary saved: ', binaryImagePath]);
        disp(['Filled binary saved: ', filledImagePath]);

    catch ME
        % Display an error message if something goes wrong
        warning(['Error processing ', imageFiles(k).name, ': ', ME.message]);
    end
end

disp('Processing complete. Binary and filled images saved in respective folders.');
